package com.team.merchant.service;

import com.team.merchant.domain.vo.StatsMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class StatsService {
    
    private final StringRedisTemplate redisTemplate;
    
    // Redis Key常量
    private static final String GLOBAL_STATS_KEY = "stats:summary";
    private static final String ORDER_BY_TYPE_KEY = "stats:orders_by_type";
    private static final String REVENUE_PREFIX = "stats:revenue:";
    private static final String LEADERBOARD_KEY = "stats:leaderboard";
    
    /**
     * 获取最新的统计数据
     * @return 统计数据消息
     */
    public StatsMessage getLatestStats() {
        try {
            // 1. 获取全局统计数据
            Map<Object, Object> globalStats = redisTemplate.opsForHash().entries(GLOBAL_STATS_KEY);
            Long totalOrders = Long.parseLong(String.valueOf(globalStats.getOrDefault("total_orders", "0")));
            Long totalRevenue = Long.parseLong(String.valueOf(globalStats.getOrDefault("total_revenue", "0")));
            
            // 2. 获取分类订单量
            Set<ZSetOperations.TypedTuple<String>> ordersByTypeWithScores = 
                    redisTemplate.opsForZSet().rangeWithScores(ORDER_BY_TYPE_KEY, 0, -1);
            
            // 3. 构建分类统计数据
            List<StatsMessage.CategoryStat> categoryStats = new ArrayList<>();
            if (ordersByTypeWithScores != null) {
                for (ZSetOperations.TypedTuple<String> tuple : ordersByTypeWithScores) {
                    String type = tuple.getValue();
                    Long orders = tuple.getScore().longValue();
                    
                    // 获取该类型的收入
                    String revenueStr = redisTemplate.opsForValue().get(REVENUE_PREFIX + type);
                    Long revenue = revenueStr != null ? Long.parseLong(revenueStr) : 0L;
                    
                    categoryStats.add(StatsMessage.CategoryStat.builder()
                            .type(type)
                            .orders(orders)
                            .revenue(revenue)
                            .build());
                }
            }
            
            // 4. 获取收入排行榜
            Set<String> leaderboardSet = redisTemplate.opsForZSet().reverseRange(LEADERBOARD_KEY, 0, -1);
            List<String> leaderboard = leaderboardSet != null ? 
                    new ArrayList<>(leaderboardSet) : Collections.emptyList();
            
            // 5. 构建并返回消息
            return StatsMessage.builder()
                    .totalOrders(totalOrders)
                    .totalRevenue(totalRevenue)
                    .categoryStats(categoryStats)
                    .leaderboard(leaderboard)
                    .build();
            
        } catch (Exception e) {
            log.error("获取统计数据失败: {}", e.getMessage());
            return StatsMessage.builder()
                    .totalOrders(0L)
                    .totalRevenue(0L)
                    .categoryStats(Collections.emptyList())
                    .leaderboard(Collections.emptyList())
                    .build();
        }
    }
} 